import { platform } from '../utils'

class RcsClient {
  constructor () {
    this.webContainer = (platform.is('iPhone') ? window.navigator.WebContainer : window.WebContainer) || {}
    this.rcsBackId = ''
    this.rcsCallCount = 0
  }
  /**
   * [call 调用RCS客户端注入的的H5方法]
   * window.RCS在static/javascript/rcs.js中引入
   * @param  {[string]}    apiName [RCS注入的方法名称]
   * @param  {...[type]} params  [调用参数]
   * @return {[type]}            [description]
   */
  call (apiName, ...params) {
    const rcsMethod = this.webContainer[apiName]

    if (!rcsMethod) {
      console.error('can\'t found RCS method ' + apiName)
    } else {
      try {
        for (let i = 0, len = params.length; i < len; i++) {
          let param = params[i]
          if (typeof param === 'object') {
            if (param.backFunc) {
              param.backFunc = 'window.RCS.cb.' + apiName
            }
            params[i] = JSON.stringify(param)
          }
          if (param === 'rcsCallBack') {
            params[i] = 'window.RCS.cb.' + apiName
          }
        }
        // alert(Object.prototype.toString.call(params))
        // alert(Object.prototype.toString.call(params[0]))
        // alert(params)
        rcsMethod.apply(this.webContainer, params)
      } catch (e) {
        console.error(e)
        alert(e)
      }
    }
  }

  getWebContainer () {
    return this.webContainer
  }

  getRcsBackId () {
    return this.rcsBackId + '-' + (this.rcsCallCount++)
  }

  /**
   * [linkToRcs 将vue组件与封装rcsclient关联 ]
   * @param  {[type]} component [vue组件的实例]
   * @return {[type]}           [description]
   * 方法中做以下事情
   * 为vue组件增加rcsBackId字段
   * 为rcsclint实例增加vue组件实例引用,方便rcs回调函数访问vue组件
   */
  linkToRcs (component) {
    try {
      window.RCS = window.RCS || {}
      const rcsRoot = window.RCS
      const rcsBackId = '@RCSBACKID@-' + component.$vnode.tag + String.prototype.replace.call(Math.random(), '0.', '-')

      this.rcsBackId = rcsBackId
      rcsRoot[this.rcsBackId] = component
      component._rcsBackId = rcsBackId
    } catch (e) {
      alert(e)
    }
  }

  /**
   * [hasMethod 判断是否注入了相应方法]
   * @param  {[type]}  mthodName [description]
   * @return {Boolean}           [description]
   */
  hasMethod (methodName) {
    return this.webContainer[methodName] && true
  }
}

export default RcsClient
